﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.AspNetCore.SignalR.Client;
using System.Threading.Channels;

namespace Zocono.WCS.Admin.Common
{
    public class SignalRClient
    {
        HubConnection connection1 = GetConnection("MENGMENG");
        //HubConnection connection2 = GetConnection("client2");
        //HubConnection connection3 = GetConnection("client3");
        //HubConnection connection4 = GetConnection("client4");

        public SignalRClient()
        {
            var unused = InitAsync();
        }

        static HubConnection GetConnection(string name)
        {
            var connection = new HubConnectionBuilder().WithUrl("https://localhost:44371//equipmentSignalRService").Build();
            //断线重连
            connection.Closed += async (sender) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);
                await connection.StartAsync();
            };
            //注册服务端响应
            connection.On<string>("CallByHub", (str) =>
            {
                Console.WriteLine($" I   am  {name}服务端传来消息:{str}");
            });
            return connection;
        }

        public async Task InitAsync()
        {
            await connection1.StartAsync();
            //await connection2.StartAsync();
            //await connection3.StartAsync();
            //await connection4.StartAsync();
        }

        /// <summary>
        /// 接收服务端数据
        /// </summary>
        /// <returns></returns>
        public async Task ReceiveByServerAsync()
        {
            var reader = await connection1.StreamAsChannelAsync<string>("SendStream");
            await Task.Run(async () =>
            {
                while (await reader.WaitToReadAsync())
                {
                    while (reader.TryRead(out var str))
                    {
                        global::System.Console.WriteLine(str);
                        await Task.Delay(100);
                    }
                }
            });
        }



        //发送到服务端
        public async Task SendToServiceAsync()
        {
            var channel = Channel.CreateUnbounded<string>();
            await connection1.SendAsync("GetClientStream", channel.Reader);
            //await Task.Run(async () =>
            //{
            //    //var lst = File.ReadAllLines("003.txt");
            //    //foreach (var line in lst)
            //    //{
            while (true)
            {

                await channel.Writer.WriteAsync("MengMengZZ");
            }
            //    //    await Task.Delay(10);
            //    //}
            //});

        }

    }
}
